
export default {
  components: {
  },
  props: {
    value: String,
    nameValue: String, // 下拉选项尚未加载前显示的值。
    dataUrl: String,
    queryParams: Object,
    dataFields: Object,
    placeholder: String
  },
  data() {
    return {
      dataRows: [],
      loading: false,
      treeOptions: [], // 尚未从后台加载下拉选项前，需要先提供 treeOptions
      currValue: null,
      queryDataRows: window.$debounce(this._queryDataRows)
    }
  },
  created() {
    this.init()
  },
  mounted() {
    this.init()
  },
  watch: {
    value() {
      this.initCurrValue()
    },
    dataUrl() {
      this.init()
    },
    queryParams() {
      this.init()
    },
    dataRows(v) {
      if (v && v.length) {
        this.treeOptions = v
      } else {
        this.initCurrValue()
      }
    }
  },
  methods: {
    init() {
      this.initCurrValue()
      /*
       * 下拉面板没显示前，不从后台加载数据选项，避免在显示表单的时候，多次调用后台。
       */
      // this.queryDataRows()
    },
    initCurrValue() {
      this.currValue = this.value
      if (this.treeOptions.length == 0 && this.nameValue) {
        let option = {}
        if (this.dataFields) {
          option[this.dataFields.key] = this.value
          option[this.dataFields.title] = this.nameValue
          option[this.dataFields.id] = this.value
        } else {
          option = {key: this.value, title: this.nameValue || this.value, id: this.value}
        }
        this.treeOptions = [option]
      }
    },
    _queryDataRows() {
      this.loading = true
      this.$http.post(this.dataUrl, this.queryParams).then((rs) => {
        this.loading = false
        const result = rs.data
        if (result.success) {
          this.dataRows = result.data
        } else {
          this.dataRows = []
        }
      })
    },
    doChange(value, label, extra) {
      this.$emit('onChange', value, label, extra)
      this.$emit('input', this.currValue)
    },
    doFocus() {
      if (!this.dataRows || this.dataRows.length == 0) {
        this.queryDataRows()
      }
    }
  }
}